/*
 * @Author: Swance
 * @Date: 2023-12-14
 * @Description: 删除插件
 */

import { fabric } from 'fabric';
import { IEditor } from '@/types/global';
import { BoardSyncEvent } from '@/utils/Const.ts';

class DeletePlugin {
  public canvas: fabric.Canvas;
  public editor: IEditor;
  isViewer: boolean;
  static pluginName = 'DeletePlugin';
  static apis = ['delete'];
  public hotkeys: string[] = ['delete', 'backspace'];
  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
    this.init();
  }

  init() {
    this.editor.on(BoardSyncEvent.type2, (data: any) => {
      this.isViewer = data.myRole === 2;
    });
  }

  // 删除选中元素
  _deleteActiveObject(activeObjects: fabric.Object[]) {
    const { canvas } = this;
    canvas.discardActiveObject();
    canvas.remove(...activeObjects);
    this.editor.emit(BoardSyncEvent.REMOVE, {
      isNewAction: true,
      oldElements: [...activeObjects],
    });
    canvas.renderAll();
  }

  delete() {
    const activeObjects = this.canvas.getActiveObjects();
    if (!activeObjects.length) return;
    const unlockActiveObject = activeObjects.filter((item) => {
      return !item.lock;
    });
    this._deleteActiveObject(unlockActiveObject);
  }

  // 清空画布
  clear() {
    const objects = this.canvas.getObjects();
    if (!objects.length) return;
    const unlockActiveObject = objects.filter((item) => {
      return !item.lock;
    });
    this._deleteActiveObject(unlockActiveObject);
  }

  // 快捷键事件
  hotkeyEvent(eventName: string, e: Event) {
    if (this.hotkeys.indexOf(eventName) >= 0 && e.type === 'keydown') {
      this.delete();
    }
  }

  // 右键菜单
  contextMenu() {
    const activeObjects = this.canvas.getActiveObjects();
    const unlockActiveObject = activeObjects.filter((item) => {
      return !item.lock;
    });
    if (unlockActiveObject.length) {
      return [
        {
          text: '删除',
          hotkey: ['Delete', 'Backspace'],
          disabled: false,
          onclick: () => this.delete(),
        },
        {
          text: '清空画布',
          disabled: false,
          onclick: () => this.clear(),
        },
      ];
    }
    if (this.isViewer) {
      return null;
    } else {
      return [
        {
          text: '清空画布',
          disabled: false,
          onclick: () => this.clear(),
        },
      ];
    }
  }
}
export default DeletePlugin;
